package com.aconcagua.samples.charts.state {
  import com.aconcagua.samples.charts.state.model.Series;
  import com.aconcagua.samples.charts.state.model.Slider;
  import com.aconcagua.samples.charts.state.model.model;
  
  import flash.events.Event;
  import flash.events.EventDispatcher;
  
  import mx.collections.ArrayCollection;
  import mx.events.CollectionEvent;
  
  public class ApplicationState extends EventDispatcher {
    private var _series: ArrayCollection;
    private var _slider: Slider;

    public function ApplicationState() {
      _series = this.createArrayCollection(refreshSeriesBinding);
    }

    /* Bindable properties */

    [Bindable("series_changed")]
    public function get series(): ArrayCollection {
      return _series;
    }

    [Bindable("slider_changed")]
    public function get slider(): Slider {
      return _slider;
    }

    /* Model update functions */    
    
    model function refreshSeries(newSeries: ArrayCollection): void {
      _series = newSeries;
      this.refreshSeriesBinding(null);
    }
    
    model function addSeries(series: Series): void {
      _series.addItem(series);
    }

    model function setSlider(theSlider: Slider): void {
      _slider = theSlider;
      this.dispatchEvent(new Event("slider_changed"));
    }
    
    /* Private functions */    
    
    private function refreshSeriesBinding(event: CollectionEvent): void {
      this.dispatchEvent(new Event("series_changed"));
    }

    //TODO: Move to a helper class
    private function createArrayCollection(changeHandler: Function): ArrayCollection {
      var collection: ArrayCollection = new ArrayCollection();
      collection.addEventListener(
        CollectionEvent.COLLECTION_CHANGE, 
        refreshSeriesBinding
      );

      return collection;      
    }
  }
}